"use client";
import React, { useEffect, useState } from "react";
import style from "./index.module.scss";
import "./index.css";
import { Button, Form, Input, Popover, Radio, message } from "antd";
import { layout } from "../PublishPost/page";
import { useForm } from "antd/es/form/Form";
import UploadImg from "@/components/UploadImg";
import {
  addVideoByUser,
  getType,
  getVideoById,
  updateVideo,
  upload,
} from "@/api";
import { useRouter, useSearchParams } from "next/navigation";
import ReactQuill from "react-quill";
import { formats, modules } from "@/configs/constant";
const PublishCourse: React.FC = () => {
  const [form] = useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [vedioUrl, setVedioUrl] = useState("");
  const [imgUrl, setImgUrl] = useState("");
  const [slectType, setSlectType] = useState("");
  const [vedioType, setVedioType] = useState([]);
  const [content, setContent] = useState("");

  const vedioId = useSearchParams().get("videoId");
  const router = useRouter();
  const getVedioType = async () => {
    const res = await getType({
      differ: "video",
      pageNum: 1,
      pageSize: 100,
    });
    setVedioType(res.data.data.records);
  };
  const inintVideo = async () => {
    const res = await getVideoById({ subjectId: Number(vedioId) });

    setImgUrl(res.data.data.subjectHead);
    setSlectType(res.data.data.subjectType);
    form.setFieldsValue(res.data.data);
  };
  const onFinish = async (values: any) => {
    let result: any;
    if (vedioId) {
      const res = await updateVideo({
        id: vedioId,
        subjectIsApply: values.subjectIsApply,
        subjectName: values.subjectName,
        subjectDescription: values.subjectDescription,
        subjectHead: imgUrl,
        videoLink: vedioUrl,
        subjectType: slectType,
        subjectStatus: 0,
        userId: Number(localStorage.getItem("userId")),
      });
      result = res;
    } else {
      const res = await addVideoByUser({
        subjectIsApply: values.subjectIsApply,
        subjectName: values.subjectName,
        subjectDescription: content,
        subjectHead: imgUrl,
        subjectType: slectType,
        userId: Number(localStorage.getItem("userId")),
      });
      result = res;
    }

    if (result.data.code === 200) {
      form.resetFields();
      setImgUrl("");
      setSlectType("");
      message.success(vedioId ? "编辑成功" : "发布成功");
      router.push("/PersonalCourse");
    } else {
      message.error(result.data.data.msg);
    }
  };
  async function uploadCom(e: React.ChangeEvent<HTMLInputElement>, t: string) {
    if (t === "img") {
      setLoading(true);
    }
    if (e.target.files) {
      const files = e.target.files[0];
      var formData = new FormData();
      formData.append("files", files);
      const response = await upload(formData);
      if (response.data.code === 200) {
        if (t === "img") {
          setImgUrl(response.data.data[0]);
          setLoading(false);
        } else if (t === "vedio") {
          setVedioUrl(response.data.data[0]);
        }
        message.success(response.data.msg);
      } else {
        message.error(response.data.msg);
      }
    }
  }
  const typeList = () => {
    return (
      <div className={style["listContainer"]}>
        {vedioType.map((item: any) => (
          <div
            className={style["item"]}
            onClick={(e) => setSlectType(e.currentTarget.innerHTML)}
            key={item.id}
          >
            {item.typeName}
          </div>
        ))}
      </div>
    );
  };
  const handleChangeValue = (value: string) => {
    setContent(value);
  };
  useEffect(() => {
    getVedioType();
    if (vedioId) {
      inintVideo();
    }
  }, []);
  return (
    <div className={style["bg"]}>
      <div className={style["body"]}>
        {/* <div className={style["content"]}>
          <ReactQuill
            placeholder="请输入你想编辑的内容"
            theme="snow"
            value={content}
            onChange={handleChangeValue}
            formats={formats}
            modules={modules}
          />
          <div className={style["editorFooter"]}></div>
        </div> */}
        <div className={style["form"]}>
          <Form
            {...layout}
            name="nest-messages"
            onFinish={onFinish}
            style={{ maxWidth: 600 }}
            form={form}
          >
            <Form.Item name={"subjectHead"} label="编程课程封面" rules={[]}>
              <UploadImg
                onChange={(e) => uploadCom(e, "img")}
                isLoading={loading}
                imgUrl={imgUrl}
              />
            </Form.Item>

            <Form.Item name={"subjectName"} label="编程课程标题" rules={[]}>
              <Input placeholder="请输入编程课程标题" />
            </Form.Item>
            <Form.Item name={"subjectDescription"} label="编程课程描述">
              <Input placeholder="请输入编程课程描述"></Input>
            </Form.Item>
            <Form.Item name={"subjectIsApply"} label="编程课程申请" rules={[]}>
              <Radio.Group>
                <Radio value={0}>是</Radio>
                <Radio value={1}>否</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item name={"subjectType"} label="编程课程类型">
              <Popover placement="right" content={typeList()}>
                <div className={style["typeBtn"]}>
                  {slectType ? slectType : "选择分类"}
                </div>
              </Popover>
            </Form.Item>
            <Form.Item label={null} wrapperCol={{ span: 8, offset: 14 }}>
              <Button type="primary" htmlType="submit" style={{ width: 130 }}>
                {vedioId ? "修改编程课程" : "发布编程课程"}
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};
export default PublishCourse;
